import 'package:flutter/cupertino.dart';
import 'package:loxen/api/http_server/file_collection.dart';
import 'package:loxen/api/http_util.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/widget/my_switch.dart';
import 'package:provider/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:loxen/api/http_server/file_change_delete_add_select.dart';
import 'package:loxen/mode/master/file_loxen.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/widget/dash_rect_painter.dart';

class BoardDialog extends StatelessWidget {
  final String path;
  final MyValueNotifier viewmodel = MyValueNotifier();
  final Color noSelect = Color(0xFFEBECF1);
  final ScrollController _scrollController = ScrollController();
  final TextEditingController _editingController = TextEditingController();

  BoardDialog({Key key, this.path}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    viewmodel.loadData();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        viewmodel.nextData();
      }
    });
    Offset offset;
    return ChangeNotifierProvider.value(
        value: viewmodel,
        child: WillPopScope(
          onWillPop: () => Future.value(true),
          child: Listener(
              onPointerDown: (event) {
                Offset pos = event.position;
                if (offset == null || pos.dy != offset.dy || pos.dx != offset.dx) {
                  Navigator.pop(context, false);
                }
              },
              child: Scaffold(
                backgroundColor: Colors.transparent,
                body: GestureDetector(
                    onPanDown: (event) {
                      offset = event.globalPosition;
                    },
                    child: Center(
                      child: Container(
                        decoration: BoxDecoration(
                            color: Theme.of(context).backgroundColor,
                            borderRadius: BorderRadius.all(Radius.circular(25.w))),
                        height: 700.h,
                        width: 580.w,
                        child: Column(
                          children: <Widget>[
                            Stack(
                              alignment: Alignment.center,
                              overflow: Overflow.visible,
                              children: <Widget>[
                                Container(
                                  height: 120.h,
                                ),
                                Positioned(
                                    bottom: 0,
                                    child: Container(
                                      width: 330.w,
                                      height: 200.h,
                                      child: ClipRRect(
                                          borderRadius: BorderRadius.circular(10.w),
                                          child: CachedNetworkImage(
                                            imageUrl: ImageUrlUtil.getClean(path, w: 330),
                                            placeholder: (_, __) => Constants.loadingIcon(),
                                            fit: BoxFit.cover,
                                          )),
                                    ))
                              ],
                            ), //图片
                            Stack(
                              alignment: Alignment.topRight,
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(left: 75.w, right: 75.w, top: 60.h),
                                  decoration: BoxDecoration(
                                      border: Border(bottom: BorderSide(color: Color(0xFFE1E1E1)))),
                                  child: TextField(
                                    controller: _editingController,
                                    decoration: InputDecoration(
                                        hintText: '创建采集文件夹',
                                        isDense: true,
                                        contentPadding: EdgeInsets.only(bottom: 5.h),
                                        border: InputBorder.none),
                                    style: TextStyle(
                                        fontSize: 30.sp,
                                        color: Theme.of(context).textTheme.subtitle2.color),
                                  ),
                                ),
                                InkWell(
                                  onTap: () async {
                                    var value = viewmodel.value;
                                    if (_editingController.text.trim() == '') {
                                      Toast.show("输入文件名", context);
                                      return;
                                    } else {
                                      if (value != null && value.length != 0) {
                                        Toast.show("文件夹存在", context);
                                      } else {
                                        ValueNotifier<bool> select = ValueNotifier(false);
                                        bool success = await showDialog(
                                          context: context,
                                          builder: (context) {
                                            return AlertDialog(
                                              title: Text('提示'),
                                              content: Column(
                                                mainAxisSize: MainAxisSize.min,
                                                children: <Widget>[
                                                  Container(
                                                    width: double.infinity,
                                                    child: Text(
                                                      '是否创建文件夹<${_editingController.text}>',
                                                      style: TextStyle(
                                                          color: Theme.of(context)
                                                              .textTheme
                                                              .subtitle2
                                                              .color),
                                                    ),
                                                  ),
                                                  Container(
                                                    margin: EdgeInsets.only(top: 30.h),
                                                    width: double.infinity,
                                                    height: 50.h,
                                                    child: Row(
                                                      children: <Widget>[
                                                        ValueListenableProvider.value(
                                                          value: select,
                                                          builder: (context, _) {
                                                            return MySwitch(
                                                                activeColor:
                                                                    Theme.of(context).primaryColor,
                                                                value: context.watch<bool>(),
                                                                onChanged: (value) {
                                                                  select.value = value;
                                                                });
                                                          },
                                                        ),
                                                        Text(
                                                          '是否公开',
                                                          style: TextStyle(
                                                            fontSize: 28.sp,
                                                            color: Color(0xFF999999),
                                                          ),
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                ],
                                              ),
                                              actions: <Widget>[
                                                Row(
                                                  children: <Widget>[
                                                    FlatButton(
                                                      child: Text(StringResources.qu_xiao),
                                                      onPressed: () => Navigator.of(context).pop(),
                                                    ),
                                                    FlatButton(
                                                      child: Text(StringResources.que_ding),
                                                      onPressed: () {
                                                        Navigator.of(context).pop(true);
                                                      },
                                                    ),
                                                  ],
                                                )
                                              ],
                                            );
                                          },
                                        );
                                        if (success!=null && success) {
                                          viewmodel.createFile(
                                              _editingController.text, !select.value);
                                        }
                                      }
                                    }
                                  },
                                  child: Container(
                                    margin: EdgeInsets.only(right: 75.w, top: 60.h),
                                    width: 40.w,
                                    height: 40.w,
                                    child: CustomPaint(
                                      painter: DashRectPainter(),
                                      child: Padding(
                                        padding: EdgeInsets.all(5.w),
                                        child: Image.asset(
                                          'images/create@2x.png',
                                          fit: BoxFit.fitWidth,
                                        ),
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            ), //输入框
                            Builder(builder: (context) {
                              var data = context
                                  .select<MyValueNotifier, List<FileLoxen>>((value) => value.value);
                              if (data != null && data.length > 0) {
                                _editingController.addListener(() {
                                  context.read<MyValueNotifier>().findFile(_editingController.text);
                                });
                                return Container(
                                  width: double.infinity,
                                  height: 270.h,
                                  child: getListView(context, data),
                                );
                              }
                              return Container(
                                width: double.infinity,
                                height: 270.h,
                                child: Constants.empty,
                              );
                            }), //文件夹列表
                            Padding(
                              padding: EdgeInsets.only(top: 60.h),
                              child: SizedBox(
                                  child: FlatButton(
                                    onPressed: () {
                                      viewmodel.collectionToFile(path, onSuccess: () {
                                        Navigator.pop(context, true);
                                      }, onError: (error) {
                                        Toast.show(error, context);
                                      });
                                    },
                                    child: Text(
                                      StringResources.cai_ji,
                                      style: TextStyle(
                                          color: Theme.of(context).textTheme.subtitle1.color,
                                          fontSize: 30.sp),
                                    ),
                                    color: Theme.of(context).primaryColor,
                                  ),
                                  width: 240.w,
                                  height: 80.h),
                            )
                          ],
                        ),
                      ),
                    )),
              )),
        ));
  }

  Widget getListView(BuildContext context, List<FileLoxen> datas) {
    return ListView.builder(
        controller: _scrollController,
        itemCount: datas.length,
        itemBuilder: (context, index) {
          var data = datas[index];
          return Padding(
            padding: EdgeInsets.only(top: 30.h, left: 75.w, right: 75.w),
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                viewmodel.select(data);
              },
              child: Row(
                children: <Widget>[
                  Builder(builder: (context) {
                    bool select =
                        context.select<MyValueNotifier, bool>((value) => data.select == 0);
                    return Container(
                      width: 25.w,
                      height: 25.w,
                      margin: EdgeInsets.only(right: 30.w),
                      decoration: BoxDecoration(
                          color: select ? noSelect : Theme.of(context).primaryColor,
                          borderRadius: BorderRadius.all(Radius.circular(25.w))),
                    );
                  }),
                  Expanded(
                      child: Text(
                    data.name,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        fontSize: 30.sp, color: Theme.of(context).textTheme.subtitle2.color),
                  )),
                  Text(data.num.toString(),
                      style: TextStyle(fontSize: 30.sp, color: Color(0xFF82868E)))
                ],
              ),
            ),
          );
        });
  }
}

class MyValueNotifier extends ChangeNotifier
    with FileChangeDeleteAddSelectMixin, FileCollectionMixin {
  bool next = false;
  int page = 1;
  List<FileLoxen> _value;
  List<FileLoxen> _search;
  List<FileLoxen> value;
  FileLoxen selectFile;

  void collectionToFile(String path, {Function() onSuccess, Function(String e) onError}) {
    if (selectFile != null) {
      collection('idea-picture', selectFile.id.toString(), null, path).listen((event) {
        if (event != null && event > 0) {
          if (onSuccess != null) onSuccess.call();
        } else {
          if (onError != null) onError.call("未知异常");
        }
      }, onError: (error, stack) {
        print(error);
        if (error is ServiceException) {
          if (onError != null) onError.call(error.data['data']['msg'].toString());
        } else {
          if (onError != null) onError.call(error.toString());
        }
      });
    }
  }

  void createFile(String name, bool select) {
    fileAdd(name, '3', select).listen((event) {
      if (event != null) {
        var file = FileLoxen(
            id: event, cover: '', name: name, num: 0, canEdit: 1, isHide: select, myHide: select);
        _value.add(file);
        value.add(file);
        notifyListeners();
      }
    }, onError: (error, stack) {
      print(error);
      print(stack);
    });
  }

  void findFile(String text) {
    if (text.trim() == '') {
      value = _value;
    } else {
      _search = _value.where((element) => element.name.startsWith(text)).toList();
      value = _search;
    }
    notifyListeners();
  }

  void select(FileLoxen fileLoxen) {
    selectFile = fileLoxen;
    _value.forEach((element) => element.select = 0);
    fileLoxen.select = 1;
    notifyListeners();
  }

  void nextData() {
    if (next) {
      page += 1;
      fileSelect('3', page: page.toString()).listen((event) {
        next = event.data.next.trim() != '';
        _value = _value.take(_value.length).toList();
        _value.addAll(event.data.results);
        notifyListeners();
      }, onError: (error, stack) {
        print(error);
        print(stack);
      });
    }
  }

  void loadData() {
    fileSelect('3', page: page.toString()).listen((event) {
      next = event.data.next.trim() != '';
      _value = event.data.results;
      value = _value;
      notifyListeners();
    }, onError: (error, stack) {
      print(error);
      print(stack);
    });
  }
}
